package com.example.node.message;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/*
 * @className: ResponseAllFuture
 * @author: chentao
 * @date: 2025/10/25 下午5:28
 * @Version: 1.0
 * @description:
 */
public class ResponseAllFuture {

    private String requestId;

    private Request request;

    private volatile Object lock = new Object();

    private volatile boolean isDone = false;

    private AtomicInteger count = null;

    private List<Response> responses = new ArrayList<>();

    public ResponseAllFuture(Request request, AtomicInteger count) {
        this.request = request;
        this.requestId = request.getRequestId();
        this.count = count;
    }

    public int put(Response response) {
        synchronized (lock) {
            this.responses.add(response);
            int i = this.count.decrementAndGet();
            if (i == 0){
                isDone = true;
                lock.notify();
            }
            return i;
        }
    }

    public List<Response> get() throws Exception {
        synchronized (lock) {
            if (isDone) {
                return responses;
            } else {
                lock.wait(request.getTimeout());
                return responses;
            }
        }
    }
}
